<template>
  <div class="login-page">
    <div class="login-container">
      <div class="login-card">
        <div class="login-header">
          <h1 class="login-title">用户登录</h1>
          <p class="login-subtitle">欢迎回到娱乐票务系统</p>
        </div>
        
        <form @submit.prevent="handleLogin" class="login-form">
          <div class="form-group">
            <label for="account" class="form-label">用户名或邮箱</label>
            <input
              id="account"
              v-model="form.account"
              type="text"
              class="form-input"
              :class="{ 'error': errors.account }"
              placeholder="请输入用户名或邮箱"
              required
            />
            <span v-if="errors.account" class="error-message">{{ errors.account }}</span>
          </div>
          
          <div class="form-group">
            <label for="password" class="form-label">密码</label>
            <div class="password-input">
              <input
                id="password"
                v-model="form.password"
                :type="showPassword ? 'text' : 'password'"
                class="form-input"
                :class="{ 'error': errors.password }"
                placeholder="请输入密码"
                required
              />
              <button
                type="button"
                @click="showPassword = !showPassword"
                class="password-toggle"
              >
                {{ showPassword ? '隐藏' : '显示' }}
              </button>
            </div>
            <span v-if="errors.password" class="error-message">{{ errors.password }}</span>
          </div>
          
          <div class="form-options">
            <label class="checkbox-label">
              <input v-model="form.remember" type="checkbox" class="checkbox">
              <span class="checkbox-text">记住我</span>
            </label>
            <!-- 暂未提供找回密码功能，移除无效链接 -->
          </div>
          
          <button
            type="submit"
            class="login-button"
            :disabled="userStore.loading"
          >
            <span v-if="userStore.loading" class="loading-spinner"></span>
            {{ userStore.loading ? '登录中...' : '登录' }}
          </button>
          
          <div v-if="userStore.error" class="error-alert">
            {{ userStore.error }}
          </div>
        </form>
        
        <div class="login-footer">
          <p class="register-prompt">
            还没有账号？
            <RouterLink to="/register" class="register-link">立即注册</RouterLink>
          </p>
          
          <div class="demo-info">
            <h4>演示说明</h4>
            <p>请先注册用户，然后使用用户名或邮箱登录</p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { useToastStore } from '@/stores/toast'
import { useFormValidator, required, minLength, custom } from '@/utils/useFormValidator'

const router = useRouter()
const userStore = useUserStore()
const toast = useToastStore()

const showPassword = ref(false)

const form = reactive({
  account: '',
  password: '',
  remember: false
})

const { errors, validate } = useFormValidator(form, {
  account: [
    required('请输入用户名或邮箱'),
    custom((v) => {
      if (String(v).includes('@')) {
        return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)
      }
      return /^[A-Za-z0-9_]{3,20}$/.test(v)
    }, '用户名需为3-20位字母/数字/下划线或有效邮箱')
  ],
  password: [required('请输入密码'), minLength(6, '密码长度至少6位')]
})

const handleLogin = async () => {
  if (!validate()) return
  
  const result = await userStore.login({
    usernameOrEmail: form.account,
    password: form.password,
    remember: form.remember
  })
  
  if (result.success) {
    // 登录后拉取个人资料以获得用户ID
    try { await userStore.fetchProfile() } catch (_) {}
    // 登录成功，跳转到首页或之前的页面
    const redirect = router.currentRoute.value.query.redirect || '/'
    toast.success('登录成功')
    router.push(redirect)
  } else if (userStore.error) {
    toast.error(userStore.error)
  }
}
</script>

<style lang="scss" scoped>
.login-page {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.login-container {
  width: 100%;
  max-width: 400px;
}

.login-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  padding: 40px;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-title {
  font-size: 28px;
  font-weight: 600;
  color: #333;
  margin-bottom: 8px;
}

.login-subtitle {
  color: #666;
  font-size: 14px;
}

.login-form {
  .form-group {
    margin-bottom: 20px;
  }
  
  .form-label {
    display: block;
    margin-bottom: 6px;
    font-weight: 500;
    color: #333;
  }
  
  .form-input {
    width: 100%;
    padding: 12px 16px;
    border: 2px solid #e1e5e9;
    border-radius: 8px;
    font-size: 16px;
    transition: border-color 0.3s;
    
    &:focus {
      outline: none;
      border-color: #667eea;
    }
    
    &.error {
      border-color: #e74c3c;
    }
  }
  
  .password-input {
    position: relative;
    
    // 为了避免遮挡，给输入框右侧预留空间
    .form-input {
      padding-right: 64px;
    }
    
    .password-toggle {
      position: absolute;
      right: 12px;
      top: 50%;
      transform: translateY(-50%);
      background: none;
      border: none;
      color: #666;
      cursor: pointer;
      font-size: 14px;
      
      &:hover {
        color: #333;
      }
    }
  }
  
  .error-message {
    display: block;
    color: #e74c3c;
    font-size: 14px;
    margin-top: 4px;
  }
}

/* 隐藏 Windows Edge/IE 的内置“显示密码”与清除图标，避免与自定义按钮重叠 */
input[type="password"]::-ms-reveal, 
input[type="password"]::-ms-clear {
  display: none;
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  cursor: pointer;
  
  .checkbox {
    margin-right: 8px;
  }
  
  .checkbox-text {
    font-size: 14px;
    color: #666;
  }
}

.forgot-link {
  color: #667eea;
  text-decoration: none;
  font-size: 14px;
  
  &:hover {
    text-decoration: underline;
  }
}

.login-button {
  width: 100%;
  padding: 14px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: transform 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
  
  &:hover:not(:disabled) {
    transform: translateY(-2px);
  }
  
  &:disabled {
    opacity: 0.7;
    cursor: not-allowed;
  }
}

.loading-spinner {
  width: 16px;
  height: 16px;
  border: 2px solid transparent;
  border-top: 2px solid white;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-right: 8px;
}

@keyframes spin {
  to {
    transform: rotate(360deg);
  }
}

.error-alert {
  background: #fee;
  color: #e74c3c;
  padding: 12px;
  border-radius: 6px;
  margin-top: 16px;
  text-align: center;
  font-size: 14px;
}

.login-footer {
  margin-top: 30px;
  text-align: center;
}

.register-prompt {
  color: #666;
  font-size: 14px;
  margin-bottom: 20px;
}

.register-link {
  color: #667eea;
  text-decoration: none;
  font-weight: 500;
  
  &:hover {
    text-decoration: underline;
  }
}

.demo-info {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  
  h4 {
    margin: 0 0 8px 0;
    color: #333;
    font-size: 14px;
  }
  
  p {
    margin: 4px 0;
    font-size: 13px;
    color: #666;
  }
}
</style>